package crons

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"hotgo/internal/dao"
	"hotgo/internal/library/cron"
	"hotgo/internal/model/entity"
)

// 自动填充 store_member 表
func init() {
	cron.Register(AutoStoreMember)
}

var AutoStoreMember = &cAutoStoreMember{name: "auto_store_member"}

type cAutoStoreMember struct {
	name string
}

func (c *cAutoStoreMember) GetName() string {
	return c.name
}

// Execute 执行任务
func (c *cAutoStoreMember) Execute(ctx context.Context, parser *cron.Parser) (err error) {
	// 查询所有门店
	var storeList []*entity.Store
	if err = dao.Store.Ctx(ctx).Scan(&storeList); err != nil {
		parser.Logger.Warning(ctx, "cron AutoStoreMember Execute err: ", err)
		return
	}
	for _, store := range storeList {
		// 根据手机号查询门店管理员
		var member entity.AdminMember
		if err = dao.AdminMember.Ctx(ctx).Where(dao.AdminMember.Columns().Mobile, store.Phone).WhereIn(dao.AdminMember.Columns().RoleId, []int{213}).Scan(&member); err != nil {
			parser.Logger.Warning(ctx, "cron AutoStoreMember Execute err: ", err)
			continue
		}
		// storeMember表中不存在就插入
		count, err := dao.StoreMember.Ctx(ctx).Where(dao.StoreMember.Columns().StoreId, store.Id).Where(dao.StoreMember.Columns().MemberId, member.Id).Count()
		if err != nil {
			parser.Logger.Warning(ctx, "cron AutoStoreMember Execute err: ", err)
			continue
		}
		if count == 0 {
			if _, err = dao.StoreMember.Ctx(ctx).Insert(g.Map{
				dao.StoreMember.Columns().StoreId:  store.Id,
				dao.StoreMember.Columns().MemberId: member.Id,
				dao.StoreMember.Columns().IsAdmin:  true,
			}); err != nil {
				parser.Logger.Warning(ctx, "cron AutoStoreMember Execute err: ", err)
				continue
			}
		}
	}
	return nil
}
